// 导出角色子仓库
export default {
    namespaced: true,
    modules: {

    },
    state: {
        list: [],
        isInit: false //标识角色数据list是否已经初始化过
    },
    mutations: {
        // 并且它会接受 state 作为第一个默认参数：
        _init(state, list) {
            state.list = list;
            state.isInit = true;
        },
        _add(state, role) {
            state.list.push(role);
        },
        _remove(state, role_id) {
            state.list.splice(
                state.list.findIndex((item) => item.role_id === role_id),
                1
            );
        },
        _update(state, role) {
            state.list.splice(
                state.list.findIndex((item) => item.role_id === role_id),
                1, role
            );
        }
    },
    actions: {
        /* 
        Action 提交的是 mutation，而不是直接变更状态。
        Action 可以包含任意异步操作。 
        */
        async init({
            rootState: {
                http
            },
            commit,
            state
        }) {
            if (state.isInit) return;
            const list = await http({
                method: "get",
                url: '/role/all'
            });
            commit("_init", list);
        },
        async add({
            rootState: {
                http
            },
            commit,
            state
        }, role) {
            role.role_id = await http({
                method: "post",
                url: '/role/add',
                data: role
            });
            commit("_add", role);
        },
        async remove({
            rootState: {
                http
            },
            commit
        }, role_id) {
            await http({
                method: "post",
                url: `/role/remove/${role_id}`,
            });
            commit("_remove", role_id);
        },
        async update({
            rootState: {
                http
            },
            commit,
            state
        }, role) {
            await http({
                method: "post",
                url: '/role/update',
                data: role
            });
            commit(" _update", role);
        }
    }
}